/******************************************************************************
*
* This file is part of FreeTrack (http://code.google.com/p/qtfreetrack).
* BY Willy Gardiol (willy@gardiol.org)
*
* FreeTrack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FreeTrack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/

#include "filebrowser.h"
#include "ftvboxlayout.h"
#include "fthboxlayout.h"

#include "ftpushbuttonicon.h"
#include "ftlabel.h"
#include "ftlist.h"
#include "ftmessagebox.h"
#include "ftlineedit.h"

QString FileBrowser::browseFilename(FileBrowser::mode m,
                                    const QString & title,
                                    const QString & default_path,
                                    const QStringList & filters,
                                    QDir::Filters dir_filter)
{
    FileBrowser dialog( m, title, default_path, filters, dir_filter );
    if ( dialog.exec() )
        return dialog.getFilename();
    return "";
}

FileBrowser::FileBrowser(FileBrowser::mode m,
                         const QString &title,
                         const QString &default_path,
                         const QStringList &filters,
                         QDir::Filters dir_filter) :
    RotatingDialog()
{
    _mode = m;

    // Setup initial path and file names
    QFileInfo fi( default_path );
    QString filename = "";
    if  ( fi.isDir() )
        path = QDir(default_path);
    else
    {
        filename = fi.fileName();
        path = QDir( fi.canonicalPath() );
    }
    path.setNameFilters( filters );
    path.setFilter( dir_filter | QDir::NoDotAndDotDot );
    path.setSorting( QDir::Name | QDir::IgnoreCase | QDir::DirsFirst );

    // Build the dialog widgets
    items_list = new FTList();
    connect( items_list, SIGNAL(stringSelected(QString)),
             this, SLOT(itemSelected(QString)));

    directoryUp_button = new FTPushButtonIcon(QIcon( ":/misc/level-up.png"),FTControls::IconBig );
    connect( directoryUp_button, SIGNAL(clicked()),
             this, SLOT(directoryUp()) );

    cancel_button = new FTPushButtonIcon( QIcon( ":/misc/cancel.png" ),FTControls::IconBig);
    connect( cancel_button, SIGNAL(clicked()),
             this, SLOT( reject()) );

    folder_label = new FTLabel();
    caption_label = new FTLabel(title);

    if ( _mode == FileBrowser::loadMode )
    {
        select_button = new FTPushButtonIcon( QIcon(":/misc/load.png"),FTControls::IconBig);
        // Hide save controls when in "open" mode
        filename_edit = NULL;
    }
    else
    {
        select_button = new FTPushButtonIcon( QIcon(":/misc/save.png"),FTControls::IconBig);
        filename_edit = new FTLineEdit(filename);
    }
    connect( select_button, SIGNAL(clicked()),
             this, SLOT(checkFilename()) );

    // Show current folder in view
    populateList();
}

void FileBrowser::checkFilename()
{
    QString selected_item = getFilename();
    QFileInfo item_info( selected_item );
    // Load mode: check that selected file does exists and matches the type set in QDir
    if ( _mode == FileBrowser::loadMode )
    {
        if ( !item_info.exists() )
            return;
    }
    else // Save mode: check that file does not exists, or ask for overwrite.
    {
        if ( item_info.exists() )
            if ( !FTMessageBox::Yesno(tr("Replace file?"),
                                     tr("File exists. Overwrite?") + "("+selected_item+")") )
                return;
    }
    accept();
}

void FileBrowser::directoryUp()
{
    if ( path.cdUp() )
        populateList();
}

void FileBrowser::itemSelected(QString user_selected_file )
{
    QString user_selected_filepath = path.filePath( user_selected_file );
    QFileInfo fi( user_selected_filepath );
    if ( fi.isDir() )
    {
        path.setPath( user_selected_filepath );
        populateList();
        user_selected_file = user_selected_filepath;
        if ( (filename_edit != NULL) && ((path.filter() & QDir::Files) != QDir::Files ) )
            filename_edit->setText( user_selected_file );
    }
    else if (filename_edit != NULL)
        filename_edit->setText( user_selected_file );
}

void FileBrowser::populateList()
{
    items_list->clear();
    if ( path.isRoot() )
    {
        QFileInfoList drives = QDir::drives();
        foreach (const QFileInfo& drive, drives)
            items_list->appendString( drive.absoluteFilePath() );
    }
    items_list->appendStrings( path.entryList() );
    folder_label->setText( path.canonicalPath() );
}

QString FileBrowser::getFilename()
{
    if ( filename_edit != NULL )
        return  path.filePath( filename_edit->text() );
    else
        return  path.filePath( items_list->selectedString() );
}

QLayout* FileBrowser::createHorizontal()
{
    return createVertical();
    /*
    FTVBoxLayout* grid = new FTVBoxLayout();
    grid->addWidget( caption_label );
    FTHBoxLayout* mainGrid = new FTHBoxLayout();
    mainGrid->addWidget( items_list );
    FTVBoxLayout* rightGrid = new FTVBoxLayout();
    rightGrid->addWidget( directoryUp_button );
    rightGrid->addWidget( select_button );
    rightGrid->addWidget( cancel_button );
    mainGrid->addLayout( rightGrid );
    grid->addLayout( mainGrid, 2 );
    FTHBoxLayout* bottomGrid = new FTHBoxLayout();
    bottomGrid->addWidget( folder_label );
    if ( filename_edit != NULL )
        bottomGrid->addWidget( filename_edit );
    grid->addLayout( bottomGrid );
    return grid;*/
}

QLayout* FileBrowser::createVertical()
{
    FTVBoxLayout* grid = new FTVBoxLayout();
    grid->addWidget( caption_label );
    grid->addWidget( items_list, 2 );
    grid->addWidget( folder_label );
    if ( filename_edit != NULL )
        grid->addWidget( filename_edit );
    FTHBoxLayout* buttonGrid = new FTHBoxLayout();
    buttonGrid->addWidget( select_button );
    buttonGrid->addWidget( directoryUp_button );
    buttonGrid->addWidget( cancel_button );
    grid->addLayout( buttonGrid );
    return grid;
}
